'use strict';

/**
 * @ngdoc function
 * @name afasApp.controller:ProductCtrl
 * @description
 * # ProductCtrl
 * Controller of the afasApp
 */
angular.module('afasApp')
  .controller('ProductsCtrl', ['$scope', '$state', 'Services', function ($scope, $state, Services) {

    $scope.items = [];
    $scope.categories = [];
    $scope.units = [];
    $scope.newItem = {
      'ProductPrice': [
        {
          'Price': 0,
          'Active': 1
        }
      ]
    };

    $scope.params = {
      'include': 'product,inventory'
    };

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('stocks', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.items = results.data;
      });
    }
    getResultsPage(1);

    Services.getItems($scope.PRODUCTCATEGORY_URL, {'getall': true})
    .then(function(results){
      $scope.categories = results.data;
    });

    Services.getItems('units', {'getall': true})
    .then(function(results){
      $scope.units = results.data;
    });

    $scope.add = function () {
      // console.log($scope.newItem);
      Services.add('products', $scope.newItem)
      .then(function(results){
        // console.log(results);
        $scope.newItem = {};
        $state.go( 'products.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.delete = function (item) {
      Services.delete('products', item);
    };
  }])
  .controller('ProductCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.categories = [];
    $scope.current = {};
    $scope.currentID = $stateParams.id;
    $scope.current = Services.getItem('products', $stateParams.id);

    Services.getItems($scope.PRODUCTCATEGORY_URL)
    .then(function(results){
      $scope.categories = results.data;
    });

    $scope.update = function () {
      Services.update('products', $scope.current, $scope.currentID);
      $state.go( 'products.show', {id: $scope.currentID} );
    };
  }]);